package com.rfid.project.web;

import java.text.DateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.util.DateUtil;
import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.ProjectMilestoneChange;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectMilestoneChangeService;
import com.rfid.project.model.ProjectMilestone;
import com.rfid.project.service.ProjectMilestoneService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;
import com.rfid.project.util.StringUtil;

@Controller
public class ProjectMilestoneChangeController {

	private static final Logger logger = LoggerFactory
			.getLogger(ProjectMilestoneChangeController.class);

	@Autowired
	private ProjectMilestoneChangeService projectMilestoneChangeService;

	@Autowired
	private ProjectMilestoneService projectMilestoneService;

	@Autowired
	private PeopleService peopleService;

	@RequestMapping(value = "/projectMilestoneChangemgr")
	public String projectMilestoneChangemgr(HttpServletRequest request,
			HttpServletResponse response, Model model,
			@RequestParam(value = "projectMilestoneId", defaultValue = "-1") Long projectMilestoneId) {
		ProjectMilestone projectMilestone = this.projectMilestoneService.findOne(projectMilestoneId);
		model.addAttribute("projectMilestone", projectMilestone);
		return "projectMilestoneChangemgr";
	}

	@RequestMapping(value = "/queryProjectMilestoneChange")
	public String queryProjectMilestoneChange(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectMilestoneId", defaultValue = "-1") Long projectMilestoneId,
			@RequestParam(value = "originalDateBegin", defaultValue = "") Date originalDateBegin,
			@RequestParam(value = "originalDateEnd", defaultValue = "") Date originalDateEnd,
			@RequestParam(value = "targetDateBegin", defaultValue = "") Date targetDateBegin,
			@RequestParam(value = "targetDateEnd", defaultValue = "") Date targetDateEnd,
			@RequestParam(value = "applyPersonId", defaultValue = "-1") Long applyPersonId,
			@RequestParam(value = "applyTimeBegin", defaultValue = "") Date applyTimeBegin,
			@RequestParam(value = "applyTimeEnd", defaultValue = "") Date applyTimeEnd,
			@RequestParam(value = "applyReason", defaultValue = "") String applyReason,
			@RequestParam(value = "checkTimeBegin", defaultValue = "") Date checkTimeBegin,
			@RequestParam(value = "checkTimeEnd", defaultValue = "") Date checkTimeEnd,
			@RequestParam(value = "checkPersonId", defaultValue = "-1") Long checkPersonId,
			@RequestParam(value = "checkComment", defaultValue = "") String checkComment,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "20") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectMilestoneChange> projectMilestoneChanges = projectMilestoneChangeService
				.findAll(projectMilestoneId, originalDateBegin,
						originalDateEnd, targetDateBegin, targetDateEnd,
						applyPersonId, applyTimeBegin, applyTimeEnd,
						applyReason, checkTimeBegin, checkTimeEnd,
						checkPersonId, checkComment, status, pageNumber,
						pageSize, sort, order);
		JSONObject object = new JSONObject();
		object.put("total", projectMilestoneChanges.getTotalElements());
		JSONArray models = new JSONArray();
		for (ProjectMilestoneChange item : projectMilestoneChanges) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findProjectMilestoneChange")
	public String findProjectMilestoneChange(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		ProjectMilestoneChange projectMilestoneChange = projectMilestoneChangeService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(projectMilestoneChange, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}

	private void wrapData(ProjectMilestoneChange item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("originalDate", com.rfid.project.util.DateUtil
				.dateTheDayToString(item.getOriginalDate()));
		mod.put("targetDate", com.rfid.project.util.DateUtil
				.dateTheDayToString(item.getTargetDate()));
		mod.put("applyTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getApplyTime()));
		mod.put("applyReason", item.getApplyReason());
		mod.put("checkTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getCheckTime()));
		mod.put("statusCode", item.getStatus());
		mod.put("status", ProcessStatus.processStatusName(item.getStatus()));			
		mod.put("projectMilestoneId", item.getProjectMilestone().getId());
		mod.put("projectMilestoneName", item.getProjectMilestone().getName());
		mod.put("applyPersonId", item.getApplyPerson().getId());
		mod.put("applyPersonName", item.getApplyPerson().getName());
		
		People checkPerson = item.getCheckPerson();
		if(null == checkPerson){
			mod.put("checkPersonId", -1);
			mod.put("checkPersonName", "");
		}else{
			mod.put("checkPersonId", checkPerson.getId());
			mod.put("checkPersonName", checkPerson.getName());
		}
		mod.put("checkComment", StringUtil.getString(item.getCheckComment()));
	}

	@RequestMapping(value = "/getProjectMilestoneChange")
	public String getProjectMilestoneChange(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id) {
		ProjectMilestoneChange item = projectMilestoneChangeService
				.getProjectMilestoneChange(id);
		JSONObject mod = new JSONObject();
		mod.put("id", item.getId());
		mod.put("originalDate", com.rfid.project.util.DateUtil
				.dateAllToString(item.getOriginalDate()));
		mod.put("targetDate", com.rfid.project.util.DateUtil
				.dateAllToString(item.getTargetDate()));
		mod.put("applyTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getApplyTime()));
		mod.put("applyReason", item.getApplyReason());
		mod.put("checkTime", com.rfid.project.util.DateUtil
				.dateAllToString(item.getCheckTime()));
		mod.put("status", item.getStatus());
		mod.put("checkComment", item.getCheckComment());
		mod.put("projectMilestoneId", item.getProjectMilestone().getId());
		mod.put("projectMilestoneName", item.getProjectMilestone().getName());
		mod.put("projectId", item.getProjectMilestone().getProject().getId());
		mod.put("projectName", item.getProjectMilestone().getProject().getName());
		mod.put("applyPersonId", item.getApplyPerson().getId());
		mod.put("applyPersonName", item.getApplyPerson().getName());
		
		People checkPerson = item.getCheckPerson();
		if (null == checkPerson) {
			mod.put("checkPersonId", -1);
			mod.put("checkPersonName", "");
		} else {
			mod.put("checkPersonId", checkPerson.getId());
			mod.put("checkPersonName", checkPerson.getName());
		}

		PageJsonBean.printObject(response, mod);
		return null;
	}

	@RequestMapping(value = "/editProjectMilestoneChange", method = RequestMethod.POST)
	public String editProjectMilestoneChange(HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectMilestoneChange projectMilestoneChange, Model model,
			RedirectAttributes redirectAttributes) {
		People person = projectMilestoneChange.getApplyPerson();
		if(null == person || null == person.getId()){
			projectMilestoneChange.setApplyPerson((People)request.getSession().getAttribute("currentUser"));
		}
		projectMilestoneChangeService.saveProjectMilestoneChange(projectMilestoneChange);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/checkProjectMilestoneChange", method = RequestMethod.POST)
	public String checkProjectMilestoneChange(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			@RequestParam(value = "checkComment", defaultValue = "") String checkComment,
			@RequestParam(value = "status", defaultValue = "") String status) {
		People currentUser = (People) request.getSession().getAttribute("currentUser");
		JSONObject result = new JSONObject();
		ProjectMilestoneChange projectMilestoneChange = projectMilestoneChangeService.getProjectMilestoneChange(id);
		if (projectMilestoneChange != null
				&& projectMilestoneChange.getStatus().equals(
						ProcessStatus.FINISH_APPLY) && currentUser != null) {
			// 更新项目节点变更信息
			projectMilestoneChange.setCheckComment(checkComment);
			projectMilestoneChange.setStatus(status);
			projectMilestoneChange.setCheckTime(DateUtil.nowDate());
			projectMilestoneChange.setCheckPerson(currentUser);
			projectMilestoneChangeService.saveProjectMilestoneChange(projectMilestoneChange);

			// 更新项目节点状态信息
			ProjectMilestone projectMilestone = projectMilestoneChange.getProjectMilestone();
			projectMilestone.setPlanFinishDate(projectMilestoneChange.getTargetDate());
			projectMilestone.setPlanReviseCount(projectMilestone.getPlanReviseCount() + 1);
			projectMilestoneService.saveProjectMilestone(projectMilestone);
			result.put("success", true);
		} else {
			result.put("success", false);
		}

		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProjectMilestoneChange")
	public String delProjectMilestoneChange(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.projectMilestoneChangeService.deleteProjectMilestoneChange(id);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	@RequestMapping(value = "/checkProjectMilestoneDelay")
	public String checkProjectMilestoneDelay(HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectMilestoneChange projectMilestoneChange) {
		People checkPerson = projectMilestoneChange.getCheckPerson();
		if(null == checkPerson || null == checkPerson.getId()){
			projectMilestoneChange.setCheckPerson((People)request.getSession().getAttribute("currentUser"));
		}
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectMilestoneChangeService.checkProjectMilestoneDelay(projectMilestoneChange);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	@RequestMapping(value = "/revocationChangeApplyProjectMilestoneChangeApply")
	public String revocationChangeApplyProjectMilestoneChangeApply(HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectMilestoneChange projectMilestoneChange) {
		People checkPerson = projectMilestoneChange.getCheckPerson();
		if(null == checkPerson || null == checkPerson.getId()){
			projectMilestoneChange.setCheckPerson((People)request.getSession().getAttribute("currentUser"));
		}
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectMilestoneChangeService.revocationChangeApplyProjectMilestoneChangeApply(projectMilestoneChange);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil
				.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
